import 'package:xws/helpers/as_t.dart';

/// 消息内容类型
enum MsgType { TEXT, IMAGE }

const List<String> _msgTypes = <String>['TEXT', 'IMAGE'];

extension ExMT on MsgType {
  String get str => _msgTypes[index];
}

MsgType _getType(String k) {
  if (k == 'IMAGE')
    return MsgType.IMAGE;
  else
    return MsgType.TEXT;
}

/// 聊天室消息项
class ChatMegObj {
  ChatMegObj({
    required this.content,
    required this.conversationRelationId,
    required this.createdAt,
    required this.id,
    required this.messageType,
    required this.userId,
  });

  factory ChatMegObj.fromJson(Map<String, dynamic> jsonRes) => ChatMegObj(
        content: asT<String>(jsonRes['content']),
        conversationRelationId: asT<String>(jsonRes['conversationRelationId']),
        createdAt: asT<String>(jsonRes['createdAt']),
        id: asT<String>(jsonRes['id']),
        messageType: _getType(asT<String>(jsonRes['messageType'])),
        userId: asT<String>(jsonRes['userId']),
      );

  late String content;
  late String conversationRelationId;
  late String createdAt;
  late String id;
  late MsgType messageType;
  late String userId;
  double? boxHeight;

  DateTime get createDate => createdAt.isEmpty ? DateTime.now() : DateTime.parse(createdAt);

  String get dateStr {
    try {
      return createdAt.replaceFirst('T', ' ');
    } catch (e) {
      return createdAt;
    }
  }

  bool needShowDate(DateTime d) => createDate.difference(d).inHours >= 1;
}
